package com.tticar.invmanager.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.entity.MBrand;
import com.tticar.invmanager.entity.MMateriel;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.service.IMBrandService;
import com.tticar.invmanager.service.IMMaterielService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 存货品牌 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-06-27
 */
@Controller
@RequestMapping("/mBrand")
public class MBrandController extends BaseController {

    @Autowired
    private IMBrandService mBrandService;

    @Autowired
    private IMMaterielService materielService;

    @PostMapping
    @ResponseBody
    public MyResponseBody post(MBrand mBrand) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.ne("status", -1);
        wrapper.eq("name", mBrand.getName());
        if(mBrand.getId() != null) {
            wrapper.ne("id", mBrand.getId());
        }
        MBrand sku = this.mBrandService.selectOne(wrapper);
        if(sku != null) {
            return MyResponseBody.failure("名称已存在");
        }

        mBrandService.insertOrUpdate(mBrand);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        Wrapper wrapper = new EntityWrapper();
        wrapper.in("brand_id", ids);
        wrapper.eq("status", 0);
        int count = this.materielService.selectCount(wrapper);
        if(count > 0) {
            return MyResponseBody.failure("品牌已被存货使用，不能删除");
        }
        mBrandService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(mBrandService.selectById(id));
        return responseBody;
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(MBrand mBrand, MyPage<MBrand> page) {
        return mBrandService.selectPage(mBrand, page);
    }

    @GetMapping("edit")
    public String edit(MBrand mBrand, ModelMap modelMap) {
        modelMap.put("id", mBrand.getId());
        return "/mBrand/mBrand_edit";
    }

    @GetMapping
    public String index() {
        return "/mBrand/mBrand";
    }

}
